/**
 * 获取动态加载的组件---测试修改
 */
async function getComponents(components, configPageParams) {
  // console.log(configPageParams, 'configPageParams?.comps', components);

  if (!configPageParams?.comps) return;
  for (let item of configPageParams.comps) {
    const componentModule = await import(/* @vite-ignore */ '/src/views' + item.component);
    const component = markRaw(componentModule.default);
    components[item.name] = {
      name: item.name,
      component,
      props: {},
      events: {}
    };
    setComponentsProps(item, components, configPageParams);
  }
}

/**
 * 设置组件的属性
 * @param item 组件
 * @param components 组件集合
 * @param configPageParams  配置页面参数
 * 示例：
 * props: {
 *      detailRef:  'tableRefs.detailRef',
 *      a:"a",
 *      data:"boolean&false",
 *      $fun_upSearchParams:"(params) => configPageParams.configPageParams.tableRefs.detailRef.searchParam = params",
 *   }
 *  tableRefs.detailRef
 *    =>  tableRefs.detailRef 有特殊标识【.】那么会获取configPageParams对应中的值
 *    =>  tableRefs.detailRef  = configPageParams.tableRefs.detailRef
 *  a
 *    =>  a 为字符串，直接返回 a
 */
function setComponentsProps(item, components, configPageParams) {
  const { name, props } = item || {};
  components[name].props = {};
  components[name].events = {};

  if (props) {
    Object.keys(props).forEach(key => {
      if (key.startsWith('$fun_')) {
        // 识别 $fun_ 前缀，绑定为事件
        const eventName = key.replace('$fun_', '');
        const method = new Function('params', 'configPageParams', props[key]);
        components[name].events[eventName] = params => method(params, configPageParams);
      } else if (props[key].includes('.')) {
        components[name].props[key] = getNestedValue(configPageParams, props[key]);
      } else if (props[key].includes('&')) {
        components[name].props[key] = setComponentValue(props[key]);
      } else {
        components[name].props[key] = props[key];
      }
    });
  }
}

function setComponentValue(val) {
  const [type, defaultValue] = val.split('&');

  switch (type) {
    case 'boolean':
      return defaultValue === 'true';
    case 'int':
      return parseInt(defaultValue);
    case 'float':
      return parseFloat(defaultValue);
    case 'object':
      return JSON.parse(defaultValue);
    default:
      return defaultValue;
  }
}

function renderDynamicComponents(components, configPageParams) {
  return Object.values(components).map((comp: any) => {
    const Component = comp.component;
    console.log(comp, 'components[name].events');

    const mergedProps = {
      ...comp.props,
      ...Object.entries(comp.events || {}).reduce((acc, [event, handler]) => {
        if (typeof handler === 'function') {
          acc[`on${event.charAt(0).toUpperCase() + event.slice(1)}`] = params => {
            // console.log(`[Event Triggered] ${event}`, params);
            // console.log(handler, 'handler');

            handler(params);
          };
        }
        return acc;
      }, {})
    };

    // console.log(mergedProps, 'mergedProps');

    // 动态生成 ref 名称，如 roleRef
    const refName = comp.name + 'Ref';
    configPageParams['components'][refName] = null;
    return h(Component, {
      ...mergedProps,
      ref: el => (configPageParams['components'][refName] = el)
    });
  });
}

export { getComponents, renderDynamicComponents };
